//
//  LBMRefreshControl.swift
//  微博
//
//  Created by 刘保满 on 16/5/27.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit

enum RefreshStatue: Int {
    case Normal     //普通状态
    case Pulling    //准备刷新
    case Refreshing //正在刷新
}


private let refreshViewHeight: CGFloat = 60

class LBMRefreshControl: UIControl {
    
    
    var statue: RefreshStatue = .Normal {
        didSet{
            switch statue {
            case .Normal:
                print("下拉起飞")
                //显示箭头
                arrowicon.hidden = false
                //停止转动
                indicatorView.stopAnimating()
                
                tipLabel.text = "下拉起飞"
                
                if oldValue == .Refreshing {
                    
                    UIView.animateWithDuration(0.25, animations: { 
                        
                        var inset = self.scrollView!.contentInset
                        
//                        print(inset)
                        inset.top = inset.top - refreshViewHeight
                        print(inset.top)
                        self.scrollView?.contentInset = inset
                    })
       
                    
                }
    
                
                UIView.animateWithDuration(0.25, animations: {
                    
                    self.arrowicon.transform = CGAffineTransformIdentity
                })
    
            case .Pulling:
                print("准备起飞")
                tipLabel.text = "准备起飞"
                
                UIView.animateWithDuration(0.25, animations: { 
                    
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
   
            case .Refreshing:
                print("正在起飞")
                tipLabel.text = "正在飞ing..."
                //隐藏箭头
                arrowicon.hidden = true
                //转动菊花
                indicatorView.startAnimating()
                
                //请求网络数据
                sendActionsForControlEvents(.ValueChanged)
                
                UIView.animateWithDuration(0.25, animations: { 
                    
                    var inset = self.scrollView!.contentInset
                    print(inset)
                    inset.top = inset.top + refreshViewHeight
                    
                    self.scrollView?.contentInset = inset
        
//                    print(inset)
                })
  
            }
            
            
        }
        
 
        
    }
    
    //刷新结束后
    func endRefreshing() {
        
        let delta = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC)*0.9))
       
        dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
            self.statue = .Normal
        }
 
    }
    
    
    

    
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshViewHeight, width: ScreenWidth, height: refreshViewHeight)
        super.init(frame: rect)
        
        setupUI()
        
        
    }
    //默认报错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //将要移动到父视图
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
        
        //获取tableView
        if let myFather = newSuperview as? UIScrollView {
            
            //如果父视图是scrollView及其子类
            //要获取父视图的垂直方向的位移
            scrollView = myFather
            
            //KVO
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
            
        }
        
    }
    //键值观察着的响应方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //        print(change)
        //获取父视图的垂直方向的位移
        let offsetY = scrollView!.contentOffset.y
        
//        print(offsetY)
        let targetOffsetY = -scrollView!.contentInset.top - refreshViewHeight
        
        
//        print(targetOffsetY)  //-124
        
        //拽动
        if scrollView!.dragging {
            
            if statue == .Pulling && offsetY > targetOffsetY {
                statue = .Normal
                
            } else if statue == .Normal && offsetY < targetOffsetY {
                
                //达到临界点,变为等待刷新状态
                statue = .Pulling
            }
            
        } else {
            
            //没有被拽动
            if statue == .Pulling  {
                
                statue = .Refreshing
            }
            
        }
    }
    
    //设置UI
    private func setupUI() {
        //添加子控件
        addSubview(backImageView)
        addSubview(arrowicon)
        addSubview(tipLabel)
        addSubview(indicatorView)
        
        //设置约束
        backImageView.snp_makeConstraints { (make) in
            
            make.left.right.bottom.equalTo(self)

        }

        arrowicon.snp_makeConstraints { (make) in
            
            //水平居中,然后向左偏移30
            make.centerX.equalTo(self.snp_centerX).offset(-40)
            make.centerY.equalTo(self.snp_centerY)
            
        }
        
        tipLabel.snp_makeConstraints { (make) in
            
            make.left.equalTo(arrowicon.snp_right)
            make.centerY.equalTo(self.snp_centerY)
            
        }
        
        indicatorView.snp_makeConstraints { (make) in
            
            make.center.equalTo(arrowicon.snp_center)
        }
        
        
        
        
        
    }
    
    //用来记录父视图的属性
    var scrollView: UIScrollView?
    //懒加载子视图
    private lazy var arrowicon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    private lazy var tipLabel: UILabel = UILabel(title: "下拉起飞", font: 14, textColor: UIColor.darkGrayColor())
    
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage(named: "refreshbg"))
    
    
    
    //移除对象的属性观察
    deinit {
        
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    
    
    
    
}
